package fr.gdi.android.news;

import java.io.File;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.android.extras.ColorDialog;
import com.android.extras.ColorPickListener;

import fr.gdi.android.news.utils.Constants.Configuration;
import fr.gdi.android.news.utils.Constants.Preferences;
import fr.gdi.android.news.utils.PreferenceUtils;
import fr.gdi.android.news.utils.Utils;

public class AppearanceActivity extends PreferenceActivity implements OnPreferenceClickListener
{
    private static final int WARNING_DIALOG = 1;
    
    private boolean doNotShowAgain;
    
    private Integer appWidgetId;

    //private final static int requestSelectBackground = 1002;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.appearance);
        
        Intent launchIntent = getIntent();
        Bundle extras = launchIntent.getExtras();
        if (extras != null)
        {
            appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }
        
        setupAction(Preferences.HEADLINE_COLOR);
        setupAction(Preferences.SUMMARY_COLOR);
        setupAction(Preferences.FOOTER_COLOR);
        setupAction(Preferences.WIDGET_TITLE_COLOR);
        
        setupBackgroundPreference();
        
        int[] wids = Utils.getAllWidgetIds(this);
        if (wids.length > 0)
        {
            boolean hideWarning = PreferenceUtils.getBooleanPreference(this, Preferences.HIDE_APPEARANCE_WARNING);
            if (!hideWarning)
            {
                showDialog(WARNING_DIALOG);
            }
        }
    }
    
    @Override
    protected void onNewIntent(Intent intent)
    {
        
        super.onNewIntent(intent);
    }
    
    protected Dialog onCreateDialog(int id)
    {
        switch (id)
        {
            case WARNING_DIALOG:
                final Context ctx = this;
                
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                AlertDialog dlg = builder.create();
                dlg.setTitle(getString(R.string.appearance));
                LayoutInflater inflater = getLayoutInflater();
                View view = inflater.inflate(R.layout.appearance_warning, null);
                TextView tv = (TextView) view.findViewById(R.id.appearance_warning_text);
                tv.setText(R.string.appearance_warning_text);
                CheckBox box = (CheckBox) view.findViewById(R.id.donot_whow_again_cb);
                box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                    {
                        doNotShowAgain = isChecked;
                    }
                });
                dlg.setView(view);
                dlg.setButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.cancel();
                    }
                });
                dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog)
                    {
                        PreferenceUtils.setBooleanPreference(ctx, Preferences.HIDE_APPEARANCE_WARNING, doNotShowAgain);
                    }
                });
                return dlg;
            default:
                return null;
        }
    }
    
    private void setupAction(String key)
    {
        Preference pref = findPreference(key);
        pref.setOnPreferenceClickListener(this);
        
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        int c = prefs.getInt(key, Color.WHITE);
        Editor editor = prefs.edit();
        editor.putInt(key, c);
        editor.commit();
    }
    
    private void setupBackgroundPreference()
    {
        String key = Preferences.BACKGROUND;
        Preference pref = findPreference(key);
        key = appWidgetId != null ? PreferenceUtils.getWidgetPreferenceKey(key, appWidgetId) : key;
        pref.setOnPreferenceClickListener(this);
        
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String bg = prefs.getString(key, Configuration.DARK);
        pref.setDefaultValue(bg);
        
        /*
        Preference bPref = findPreference("BACKGROUND_FILE");
        bPref.setOnPreferenceClickListener(this);
        */
    }
    
    @Override
    public boolean onPreferenceClick(Preference preference)
    {
        final String key = preference.getKey();
        
        if (key.endsWith(Preferences.HEADLINE_COLOR) || key.endsWith(Preferences.SUMMARY_COLOR) || key.endsWith(Preferences.FOOTER_COLOR)
                || key.endsWith(Preferences.WIDGET_TITLE_COLOR))
        {
            final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            int c = prefs.getInt(key, Color.WHITE);
            ColorDialog dlg = new ColorDialog(this, false, preference, c, new ColorPickListener() {
                @Override
                public void onPick(Object tag, int color)
                {
                    Editor editor = prefs.edit();
                    editor.putInt(key, color);
                    editor.commit();
                }
            }, R.drawable.wheel);
            dlg.show();
            return true;
        }
        /*
        else if ( key.endsWith("BACKGROUND_FILE") )
        {
            Intent intent = new Intent(this, FilePickerActivity.class);

            String p = PreferenceUtils.getStringPreference(this, Preferences.BACKGROUND_FILE, appWidgetId);
            if ( !TextUtils.isEmpty(p) ) 
            {
                File f = new File(p);
                if ( f.getParentFile().exists() ) 
                {
                    intent.putExtra(FilePickerActivity.EXTRA_FILE_PATH, f.getParentFile().getPath());
                }
                else
                {
                    intent.putExtra(FilePickerActivity.EXTRA_FILE_PATH, Environment.getExternalStorageDirectory().getPath());
                }
            }
            else 
            {
                intent.putExtra(FilePickerActivity.EXTRA_FILE_PATH, Environment.getExternalStorageDirectory().getPath());
            }
    
             // Show hidden files
             //intent.putExtra(FilePickerActivity.EXTRA_SHOW_HIDDEN_FILES, true);
    
             // Only make .png files visible
             ArrayList<String> extensions = new ArrayList<String>();
             extensions.add(".png");
             extensions.add(".jpg");
             intent.putExtra(FilePickerActivity.EXTRA_ACCEPTED_FILE_EXTENSIONS, extensions);
    
             // Start the activity
             startActivityForResult(intent, requestSelectBackground);
        }
        */
        return false;
    }
    
    /*
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == requestSelectBackground) 
        {
            String path = data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH);
            PreferenceUtils.setStringPreference(this, Preferences.BACKGROUND_FILE, path);
        }
        else 
        {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
    */
}
